package cn.felord.boot;

public class DeleteDuplicates {

    /***
     * 删除排序链表中的重复元素 II
     * @param head
     * @return
     */
    public static ListNode deleteDuplicates(ListNode head) {
        ListNode dummy = new ListNode(0, head);
        ListNode cur = dummy;
        while (cur.next != null && cur.next.next != null) {
            if (cur.next.val == cur.next.next.val) {
                // 记录当前重复的值
                int val = cur.next.val;
                // 跳过所有值等于val的节点
                while (cur.next != null && cur.next.val == val) {
                    cur.next = cur.next.next;
                }
            } else {
                // 如果当前节点的下一个节点和下下个节点的值不相等，移动cur指针
                cur = cur.next;
            }
        }
        return dummy.next;
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(1);
        head.next.next = new ListNode(1);
        head.next.next.next = new ListNode(2);
        head.next.next.next.next = new ListNode(3);
        ListNode node = deleteDuplicates(head);
        System.out.println(node);

    }
}
